package cn.com.common.job.task;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStationinfoForecastEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasStationinfoForecastService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.thirdparty.entity.VExDtEntity;
import cn.com.thirdparty.entity.VExJrjyJyzEntity;
import cn.com.thirdparty.entity.VExJrjySjEntity;
import cn.com.thirdparty.entity.VExJrjyXjEntity;
import cn.com.thirdparty.service.VExDtService;
import cn.com.thirdparty.service.VExJrjyJyzService;
import cn.com.thirdparty.service.VExJrjySjService;
import cn.com.thirdparty.service.VExJrjyXjService;
import cn.com.util.TsBqUtils;

/**
 * 定时任务 同步v_ex_jrjy_jyz表， v_ex_jrjy_xj表 ，v_ex_jrjy_sj表，v_ex_dt表
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasVExJrjyProcessTask")
@DisallowConcurrentExecution
public class GasVExJrjyProcessTask {

	@Value("${gasstation.timedTask.gasVExJrjyProcessTask}")
	private String gasVExJrjyProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private GasStationinfoService gasStationinfoService;

	@Autowired
	private GasStationinfoForecastService gasStationinfoForecastService;

	@Autowired
	private VExJrjyJyzService vExJrjyJyzService;
	@Autowired
	private VExJrjySjService vExJrjySjService;
	@Autowired
	private VExJrjyXjService vExJrjyXjService;
	@Autowired
	private VExDtService vExDtService;

	public void run(String params) throws Exception {
		logger.debug("gasVExJrjyProcessTask定时任务正在执行，参数为：{}", params);

		logger.debug("application参数为gasVExJrjyProcessTask：{}", gasVExJrjyProcessTask);

		if (gasVExJrjyProcessTask.equals(Constants.JOB_STOP)) {

			logger.debug("application配置文件控制不执行gasVExJrjyProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasVExJrjyProcessTask定时任务");

		}

		LocalDate currentDate = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String formattedDate = currentDate.format(formatter);

		LocalDateTime startOfDay = LocalDateTime.of(currentDate, LocalTime.MIN);
		LocalDateTime endOfDay = LocalDateTime.of(currentDate, LocalTime.MAX);
		LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.isNotNull(GasStaytimeResultEntity::getStationId);
		queryWrapper.ge(GasStaytimeResultEntity::getMessageDisappear, startOfDay);
		queryWrapper.le(GasStaytimeResultEntity::getMessageDisappear, endOfDay);

		// queryWrapper.ne(GasStaytimeResultEntity::getFromTopic,"/videocomm/status/aiemb/1qaz");

		List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper);

		// v_ex_jrjy_jyz
		Map<String, List<GasStaytimeResultEntity>> groupedItems = list.stream()
				.collect(Collectors.groupingBy(item -> item.getStationId()));
		List<VExJrjyJyzEntity> jrjyJyzList = new ArrayList<>();

		groupedItems.forEach((category, itemsInCategory) -> {
			VExJrjyJyzEntity jrjyJyz = new VExJrjyJyzEntity();

			GasStationinfoEntity gasStationinfoEntity = gasStationinfoService.getById(category);

			if (gasStationinfoEntity != null) {
				String taxorgcode = gasStationinfoEntity.getTaxorgcode();
				SysDept sysDept = deptService.getById(taxorgcode);

				String name = gasStationinfoEntity.getName();
				jrjyJyz.setNyr(formattedDate); // 日期
				jrjyJyz.setSwjgDm(taxorgcode); // 税务机关代码
				jrjyJyz.setSwjgMc(sysDept.getName()); // 税务机关名称
				jrjyJyz.setJyzId(category); // 加油站ID
				jrjyJyz.setJyzMc(name); // 加油站名称
				jrjyJyz.setXzqhDm(taxorgcode.substring(1, 7)); // 行政区划代码
				jrjyJyz.setXzqhMc(sysDept.getManagerName()); // 行政区划名称

				BigDecimal[] resultQyJe = { new BigDecimal(0) };
				BigDecimal[] resultCyJe = { new BigDecimal(0) };
				BigDecimal[] resultHzJe = { new BigDecimal(0) };
				int[] lc = { 0 };
				BigDecimal[] resultStyJe = { new BigDecimal(0) };
				BigDecimal[] resultDfyzJe = { new BigDecimal(0) };

				BigDecimal[] resultHzJeCs = { new BigDecimal(0) };

				itemsInCategory.forEach(item -> {
					String oils = item.getOils();
					String price = item.getPrice();

					lc[0]++;
					resultHzJe[0] = resultHzJe[0].add(new BigDecimal(price));

					if ("汽油".equals(oils)) {
						// 汽油
						resultQyJe[0] = resultQyJe[0].add(new BigDecimal(price));
					} else {
						// 柴油
						resultCyJe[0] = resultCyJe[0].add(new BigDecimal(price));
					}

					boolean contains = name.contains("中国");
					boolean contains1 = name.contains("中石油");
					boolean contains2 = name.contains("中石化");

					if (contains || contains1 || contains2) {
						resultStyJe[0] = resultStyJe[0].add(new BigDecimal(price));
					} else {
						resultDfyzJe[0] = resultDfyzJe[0].add(new BigDecimal(price));
					}
				});

				jrjyJyz.setQyJe((int) Math.floor(Double.parseDouble(resultQyJe[0].toString()))); // 汽油-金额
				jrjyJyz.setCyJe((int) Math.floor(Double.parseDouble(resultCyJe[0].toString()))); // 柴油-金额

				double number = Double.parseDouble(resultHzJe[0].toString());
				jrjyJyz.setHzJe((int) Math.floor(number)); // 汇总-金额

				jrjyJyz.setLc(lc[0]); // 辆次
				jrjyJyz.setStyJe((int) Math.floor(Double.parseDouble(resultStyJe[0].toString()))); // 三桶油-金额
				jrjyJyz.setDfyzJe((int) Math.floor(Double.parseDouble(resultDfyzJe[0].toString()))); // 地方油站-金额

				// 获取预估值
				// 获取前一天日期  更新前一天的数据 当天数据设置为0
				
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, -1);
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				String previousDate = dateFormat.format(calendar.getTime());

				LambdaQueryWrapper<GasStationinfoForecastEntity> stationinfoForecastWrapper = Wrappers.lambdaQuery();

				stationinfoForecastWrapper.eq(GasStationinfoForecastEntity::getStationinfoId, category);
				stationinfoForecastWrapper.eq(GasStationinfoForecastEntity::getTime, previousDate);

				List<GasStationinfoForecastEntity> forecastEntity = gasStationinfoForecastService
						.list(stationinfoForecastWrapper);
				if (TsBqUtils.isNotNull(forecastEntity)) {
					GasStationinfoForecastEntity gasStationinfoForecastEntity = forecastEntity.get(0);

					String forecastValue = gasStationinfoForecastEntity.getForecastValue();
					BigDecimal forecastValueDecimal = new BigDecimal(forecastValue);
					// 最后预估值乘以倍数
					// 覆盖率50%以上的乘以1.6
					// 覆盖率50%乘以2
					// 覆盖率50%以下乘以2.3
					// 覆盖率100%乘以1.3

					String gasCoverage = gasStationinfoEntity.getGasCoverage();
					String gasLocation = gasStationinfoEntity.getGasLocation();

					if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
							&& !"0".equals(gasLocation)) {

						BigDecimal coverageBigDecimal = new BigDecimal(gasCoverage);
						BigDecimal locationBigDecimal = new BigDecimal(gasLocation);

						BigDecimal divide = forecastValueDecimal.divide(coverageBigDecimal, 2,
								BigDecimal.ROUND_HALF_UP);

						forecastValueDecimal = divide.multiply(locationBigDecimal);

						int comparisonResult1 = coverageBigDecimal.compareTo(locationBigDecimal);
						if (comparisonResult1 == 0) {
							forecastValueDecimal.multiply(new BigDecimal("1.3"));

						} else {

							BigDecimal bigDecimal = coverageBigDecimal.divide(locationBigDecimal, 2,
									BigDecimal.ROUND_HALF_UP);

							int comparisonResult = bigDecimal.compareTo(new BigDecimal("0.5"));
							if (comparisonResult > 0) {
								// 大于 0.5
								forecastValueDecimal.multiply(new BigDecimal("1.6"));
							} else if (comparisonResult < 0) {
								// 小于 0.5
								forecastValueDecimal.multiply(new BigDecimal("2.3"));
							} else {
								// 等于 0.5
								forecastValueDecimal.multiply(new BigDecimal("2"));
							}
						}

					} else {
						forecastValueDecimal.multiply(new BigDecimal("1.3"));
					}

					resultHzJeCs[0] = resultHzJeCs[0].add(forecastValueDecimal);
				}
				
				
				LambdaQueryWrapper<VExJrjyJyzEntity> vExJrjyJyzQueryWrapper = Wrappers.lambdaQuery();
				
				vExJrjyJyzQueryWrapper.eq(VExJrjyJyzEntity::getJyzId, category);
				vExJrjyJyzQueryWrapper.eq(VExJrjyJyzEntity::getNyr, previousDate);
				List<VExJrjyJyzEntity> vExJrjyJyzList = vExJrjyJyzService.list(vExJrjyJyzQueryWrapper);
				if(TsBqUtils.isNotNull(vExJrjyJyzList)){
					VExJrjyJyzEntity vExJrjyJyzEntity = vExJrjyJyzList.get(0);
					
					vExJrjyJyzEntity.setHzJeCs((int) Math.floor(Double.parseDouble(resultHzJeCs[0].toString())));
					try {
						
						vExJrjyJyzService.saveVExJrjyJyz(vExJrjyJyzEntity); // 写入v_ex_jrjy_jyz
					} catch (Exception e) {
						// TODO: handle exception
						logger.debug("写入更新前一天v_ex_jrjy_jyz异常:" + e.getMessage());
					}
					
				}
				// jrjyJyz.setHzJeCs((int) Math.floor(Double.parseDouble(resultHzJeCs[0].toString())));
				jrjyJyzList.add(jrjyJyz);

			}

		});

		for (VExJrjyJyzEntity vExJrjyJyzEntity : jrjyJyzList) {
			try {
				
				vExJrjyJyzService.saveVExJrjyJyz(vExJrjyJyzEntity); // 写入v_ex_jrjy_jyz
			} catch (Exception e) {
				// TODO: handle exception
				logger.debug("写入v_ex_jrjy_jyz异常:" + e.getMessage());
			}

		}

		// v_ex_jrjy_xj
		Map<String, List<VExJrjyJyzEntity>> groupedItemsJrjyJyz = jrjyJyzList.stream().collect(Collectors.groupingBy(
				item -> item.getSwjgDm() + "_" + item.getSwjgMc() + "_" + item.getXzqhDm() + "_" + item.getXzqhMc()));

		List<VExJrjyXjEntity> jrjyXjList = new ArrayList<>();
		List<VExDtEntity> dtList = new ArrayList<>();

		groupedItemsJrjyJyz.forEach((category, itemsInCategory) -> {
			VExJrjyXjEntity jrjyXj = new VExJrjyXjEntity();
			VExDtEntity dt = new VExDtEntity();

			String[] arr = category.split("_");
			jrjyXj.setNyr(formattedDate); // 日期
			jrjyXj.setSwjgDm(arr[0]); // 税务机关代码
			jrjyXj.setSwjgMc(arr[1]); // 税务机关名称
			jrjyXj.setXzqhDm(arr[0].substring(1, 7)); // 行政区划代码
			jrjyXj.setXzqhMc(arr[3]); // 行政区划名称

			BigDecimal[] resultQyJe = { new BigDecimal(0) };
			BigDecimal[] resultCyJe = { new BigDecimal(0) };
			BigDecimal[] resultHzJe = { new BigDecimal(0) };
			int[] lc = { 0 };
			BigDecimal[] resultStyJe = { new BigDecimal(0) };
			BigDecimal[] resultDfyzJe = { new BigDecimal(0) };
			int[] styz = { 0 };
			int[] dfyz = { 0 };

			itemsInCategory.forEach(item -> {
				resultQyJe[0] = resultQyJe[0].add(new BigDecimal(item.getQyJe()));
				resultCyJe[0] = resultCyJe[0].add(new BigDecimal(item.getCyJe()));
				resultHzJe[0] = resultHzJe[0].add(new BigDecimal(item.getHzJe()));

				lc[0] = lc[0] + item.getLc();
				resultStyJe[0] = resultStyJe[0].add(new BigDecimal(item.getStyJe()));
				resultDfyzJe[0] = resultDfyzJe[0].add(new BigDecimal(item.getDfyzJe()));
				Double styJe = item.getStyJe();

				if (styJe.equals(0.0)) {
					styz[0]++;
				} else {
					dfyz[0]++;
				}
			});

			jrjyXj.setQyJe((int) Math.floor(Double.parseDouble(resultQyJe[0].toString()))); // 汽油-金额
			jrjyXj.setCyJe((int) Math.floor(Double.parseDouble(resultCyJe[0].toString()))); // 柴油-金额
			jrjyXj.setHzJe((int) Math.floor(Double.parseDouble(resultHzJe[0].toString()))); // 汇总-金额

			jrjyXj.setLc(lc[0]); // 辆次
			jrjyXj.setStyJe((int) Math.floor(Double.parseDouble(resultStyJe[0].toString()))); // 三桶油-金额
			jrjyXj.setDfyzJe((int) Math.floor(Double.parseDouble(resultDfyzJe[0].toString()))); // 地方油站-金额

			dt.setNyr(formattedDate); // 日期
			dt.setSwjgDm(arr[0]); // 税务机关代码
			dt.setSwjgMc(arr[1]); // 税务机关名称
			dt.setXzqhDm(arr[0].substring(1, 7)); // 行政区划代码
			dt.setXzqhMc(arr[3]); // 行政区划名称
			dt.setQyJe((int) Math.floor(Double.parseDouble(resultQyJe[0].toString()))); // 汽油-金额
			dt.setCyJe((int) Math.floor(Double.parseDouble(resultCyJe[0].toString()))); // 柴油-金额

			dt.setJyz(styz[0] + dfyz[0]); // 加油站
			dt.setStyz(styz[0]); // 三桶油站
			dt.setDfyz(dfyz[0]); // 地方油站

			jrjyXjList.add(jrjyXj);

			dtList.add(dt);

		});

		for (VExJrjyXjEntity vExJrjyXjEntity : jrjyXjList) {
			try {
				vExJrjyXjService.saveVExJrjyXj(vExJrjyXjEntity); // 写入v_ex_jrjy_xj
			} catch (Exception e) {
				// TODO: handle exception
				logger.debug("写入v_ex_jrjy_xj异常:" + e.getMessage());
			}

		}

		for (VExDtEntity vExDtEntity : dtList) {
			try {
				vExDtService.saveVExDt(vExDtEntity); // 写入 v_ex_dt
			} catch (Exception e) {
				// TODO: handle exception
				logger.debug("写入v_ex_dt异常:" + e.getMessage());
			}

		}

		// v_ex_jrjy_sj
		VExJrjySjEntity vExJrjySjEntity = new VExJrjySjEntity();
		vExJrjySjEntity.setNyr(formattedDate);// nyr 日期

		vExJrjySjEntity.setSwjgDm("11307000000"); // 税务机关代码

		vExJrjySjEntity.setQyJe((int) Math.floor(jrjyXjList.stream().mapToDouble(VExJrjyXjEntity::getQyJe).sum())); // 汽油-金额
		vExJrjySjEntity.setCyJe((int) Math.floor(jrjyXjList.stream().mapToDouble(VExJrjyXjEntity::getCyJe).sum())); // 柴油-金额
		vExJrjySjEntity.setHzJe((int) Math.floor(jrjyXjList.stream().mapToDouble(VExJrjyXjEntity::getHzJe).sum())); // 汇总-金额

		int sum = jrjyXjList.stream().mapToInt(VExJrjyXjEntity::getLc).sum();
		vExJrjySjEntity.setLc(sum); // 辆次
		vExJrjySjEntity.setSwjgMc("国家税务总局张家口市税务局"); // 税务机关名称

		vExJrjySjEntity.setStyJe((int) Math.floor(jrjyXjList.stream().mapToDouble(VExJrjyXjEntity::getStyJe).sum())); // 三桶油-金额
		vExJrjySjEntity.setDfyzJe((int) Math.floor(jrjyXjList.stream().mapToDouble(VExJrjyXjEntity::getDfyzJe).sum())); // 地方油站-金额

		// vExJrjySjEntity.setXzqhDm("11300000000"); //行政区划代码
		// vExJrjySjEntity.setXzqhMc("张家口"); //行政区划名称

		try {
			vExJrjySjService.saveExJrjySj(vExJrjySjEntity);
			; // 写入ExJrjySj
		} catch (Exception e) {
			// TODO: handle exception
			logger.debug("写入ExJrjySj异常:" + e.getMessage());
		}

	}

}
